package com.jt.safe.config

import com.google.gson.GsonBuilder
import com.jt.safe.BuildConfig
import com.jt.safe.api.AppApi
import com.orhanobut.logger.Logger
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object Network {
    fun getUserApi(): AppApi {
        return Retrofit.Builder().baseUrl(Config.BaseApi)
            .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
            .client(getOkHttpClient()).build().create(AppApi::class.java)
    }

    /**
     * 配置http
     */
    private fun getOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder().apply {
            addInterceptor(getHeaderInterceptor())
            if (BuildConfig.DEBUG) addInterceptor(getInterceptor())
        }.build()
    }

    /**
     * 配置拦截器
     */
    private fun getInterceptor(): Interceptor {
        val rLog = object : HttpLoggingInterceptor.Logger {
            override fun log(message: String) {
                Logger.i(message)
            }
        }
        return HttpLoggingInterceptor(rLog).apply {
            level = HttpLoggingInterceptor.Level.BODY
        }
    }

    /**
     * 配置拦截器
     */
    private fun getHeaderInterceptor(): Interceptor {
        return object : Interceptor {
            override fun intercept(chain: Interceptor.Chain): Response {
                val request = chain.request();
                val httpUrl = request
                    .newBuilder()
//                    .addHeader("token", SP().getString(Config.token, "").toString())
                    .build()
                return chain.proceed(httpUrl)
            }
        }
    }
}